package com.mymall.basic.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.ftp.Ftp;
import com.mymall.basic.config.FtpClientUtil;
import com.mymall.basic.entity.UploadFileEntity;
import com.mymall.basic.service.UploadFileService;
import com.mymall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("basic/file")
public class BaseFtpUploadController {

    @Autowired
    FtpClientUtil clientUtil;


    @Autowired
    private UploadFileService uploadFileService;

    @RequestMapping("upload/ftp")
    public R upload( @RequestParam(name = "file") MultipartFile uploadFile) {

        File file = new File("");

        System.out.println(uploadFile);


        // 年月日维度见文件夹
        String toDay = DateUtil.today().replace("-", "/");
        Ftp ftp = clientUtil.getFtp();

        String uploadFilePath = "/" + toDay+"/";
        String uploadFileName = uploadFile.getOriginalFilename();

        String type = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf("."));
        String ftpFileName = IdUtil.fastSimpleUUID()+type;


        try {
            ftp.upload("/" + uploadFilePath, ftpFileName, uploadFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ftp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        UploadFileEntity fileEntity = new UploadFileEntity();
        fileEntity.setName(ftpFileName);
        fileEntity.setPath(uploadFilePath);
        fileEntity.setOriginName(uploadFile.getOriginalFilename());
        fileEntity.setType(uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf(".")));
        fileEntity.setSize(uploadFile.getSize());

        uploadFileService.save(fileEntity);


        return R.ok().put("data",fileEntity.getId());
    }

    @RequestMapping("test")
    public String upload() {

        return "success";
    }


}
